package com.hejjon.knowledgebase.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hejjon.knowledgebase.constant.Consts;
import com.hejjon.knowledgebase.constant.event.EventKeys;
import com.hejjon.knowledgebase.constant.event.EventType;
import com.hejjon.knowledgebase.entity.UserEventLog;
import com.hejjon.knowledgebase.mapper.UserEventLogMapper;
import com.hejjon.knowledgebase.model.dto.UserDTO;
import com.hejjon.knowledgebase.model.request.EventLogRequest;
import com.hejjon.knowledgebase.model.wrapper.DataGrid;
import com.hejjon.knowledgebase.service.UserEventLogService;
import com.hejjon.knowledgebase.service.UserInfoService;
import com.hejjon.knowledgebase.util.EventParamsHolder;
import com.hejjon.knowledgebase.util.Strings;
import com.hejjon.knowledgebase.util.UserHolder;
import com.hejjon.knowledgebase.vo.EventLogVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户事件日志 服务实现类
 * </p>
 *
 * @author caoshi
 * @since 2022-12-06
 */
@Service
public class UserEventLogServiceImpl implements UserEventLogService {


    private static final Logger log = LoggerFactory.getLogger(UserEventLogServiceImpl.class);

    @Resource
    private UserEventLogMapper userEventLogMapper;

    @Resource
    private UserInfoService userInfoService;

    @Override
    public void recordLog(EventType eventType, boolean isSuccess) {
        log.info(">>>>>>>>>>>>> 开始记录用户操作日志 ");
        HashMap<String, Object> paramsMap = EventParamsHolder.get();
        EventParamsHolder.remove();

        // 模板
        String template = eventType.getTemplate();
        // 设置对象
        UserEventLog log = new UserEventLog();
        log.setUserId((Long) paramsMap.get(EventKeys.INNER_USER_ID));
        log.setUsername(paramsMap.get(EventKeys.INNER_USER_NAME).toString());
        log.setEventClassify(eventType.getClassify().getClassify());
        log.setEventType(eventType.getType());
        log.setLogInfo(Strings.format(template, paramsMap));
        log.setParamsJson(JSON.toJSONString(paramsMap));
        log.setExecResult(isSuccess ? Consts.ENABLE : Consts.DISABLE);
        log.setCreateTime(LocalDateTime.now());

        userEventLogMapper.insert(log);
    }

    /**
     * 分页查询用户操作日志
     * @param request 查询入参
     * @return  用户操作日志分页列表
     */
    @Override
    public DataGrid<EventLogVO> listUserEventLog(EventLogRequest request) {
        UserDTO userDTO = UserHolder.get();
        Page<UserEventLog> page = new Page<>(request.getPage(), request.getLimit());
        LambdaQueryWrapper<UserEventLog> wrapper = new LambdaQueryWrapper<UserEventLog>()
                .eq(request.getType() != null, UserEventLog::getEventType, request.getType())
                .eq(StringUtils.isNotBlank(request.getUsername()), UserEventLog::getUsername, request.getUsername())
                .eq(StringUtils.isNotBlank(request.getLogInfo()), UserEventLog::getLogInfo, request.getLogInfo())
                .orderByDesc(UserEventLog::getCreateTime);

        Page<UserEventLog> eventLogPage = userEventLogMapper.selectPage(page, wrapper);
        Page<EventLogVO> voPage = new Page<>();
        voPage.setSize(eventLogPage.getSize());
        voPage.setCurrent(eventLogPage.getCurrent());
        voPage.setPages(eventLogPage.getPages());
        voPage.setTotal(eventLogPage.getTotal());
        List<UserEventLog> records = eventLogPage.getRecords();
        List<EventLogVO> voRecords = new ArrayList<>();
        for (UserEventLog eventLog : records) {
            EventLogVO vo = new EventLogVO();
            vo.setId(eventLog.getId());
            vo.setLogInfo(eventLog.getLogInfo());
            EventType eventType = EventType.of(eventLog.getEventType());
            String label = eventType.getLabel();
            vo.setType(label);
            vo.setUsername(userDTO.getUsername());
            vo.setNickname(userDTO.getNickname());
            vo.setIp(userDTO.getIp());
            vo.setTime(eventLog.getCreateTime());
            vo.setParamsJson(eventLog.getParamsJson());

            voRecords.add(vo);
        }
        voPage.setRecords(voRecords);
        return DataGrid.of(voPage);
    }
}
